﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using IceDog.EFCore.ContosoUniversity.Models;
using IceDog.EFCore.ContosoUniversity.Models.SchoolViewModels;

namespace IceDog.EFCore.ContosoUniversity.Pages.Students
{
    public class CreateVMModel : PageModel
    {
        private readonly IceDog.EFCore.ContosoUniversity.Data.SchoolContext _context;

        public CreateVMModel(IceDog.EFCore.ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            // TODO remove. For quick testing.
            StudentVM = new StudentViewModel
            {
                EnrollmentDate = DateTime.Now.AddYears(-10),
                FirstMidName = "Tom",
                LastName = "Howard"
            };
            return Page();
        }
        [BindProperty]
        public StudentViewModel StudentVM { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            //--这种是从数据源头控制只有需要的属性值
            var entry = _context.Add(new Student());
            entry.CurrentValues.SetValues(StudentVM);
            await _context.SaveChangesAsync();
            return RedirectToPage("./Index");
        }
    }
}